<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">

      <el-form-item label="产品"  prop="productId" >
        <el-select
          v-model="queryParams.productId"
          placeholder="请选择产品"
          clearable
          @keyup.enter.native="handleQuery"
        >
          <el-option v-for="item in productList"
                     :key="item.id"
                     :label="item.name"
                     :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="指令名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入指令名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="标识" prop="cmdHex">
        <el-input
          v-model="queryParams.cmdHex"
          placeholder="请输入指令码标识"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="rstId" prop="resultId">
        <el-input
          v-model="queryParams.resultId"
          placeholder="rstId"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>

    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['iot:cmd:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['iot:cmd:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['iot:cmd:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['iot:cmd:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="cmdList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" align="center" prop="id" />
      <el-table-column label="产品" align="center" prop="productName" />
      <el-table-column label="发起方" align="center" prop="sponsor">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.iot_message_by" :value="scope.row.sponsor"/>
        </template>
      </el-table-column>
      <el-table-column label="指令类型" align="center" prop="cmdType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.iot_message_type" :value="scope.row.cmdType"/>
        </template>
      </el-table-column>
      <el-table-column label="rstId" align="center" prop="resultId" />
      <el-table-column label="指令名称" align="center" prop="name" />
      <el-table-column label="指令码标识" align="center" prop="cmdHex" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="创建者" align="center" prop="creator" />
      <el-table-column label="创建时间" align="center" prop="createDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['iot:cmd:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="showEditCmdDialog(scope.row)"
          >生成</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="showLookCmdDialog(scope.row)"
          >查看</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['iot:cmd:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改指令对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>



      <el-form ref="form" :model="form" :rules="rules" label-width="80px">


        <el-form-item label="产品"  prop="productId" >
          <el-select
            v-model="form.productId"
            placeholder="请选择产品"
            clearable
            @keyup.enter.native="handleQuery"
          >
            <el-option v-for="item in productList"
                       :key="item.id"
                       :label="item.name"
                       :value="item.id">

            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="发起方" prop="sponsor">
          <el-select v-model="form.sponsor" placeholder="请选择发起方" clearable>
            <el-option
              v-for="dict in dict.type.iot_message_by"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="指令类型" prop="cmdType">
          <el-select v-model="form.cmdType" placeholder="请选择指令类型">
            <el-option
              v-for="dict in dict.type.iot_message_type"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="指令名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入指令名称" />
        </el-form-item>
        <el-form-item label="标识" prop="cmdHex">
          <el-input v-model="form.cmdHex" placeholder="请输入指令码标识" />
        </el-form-item>

        <el-form-item label="rstId" prop="resultId">
          <el-input v-model="form.resultId" placeholder="rstId" />
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
        <el-form-item label="创建者" prop="creator">
          <el-input v-model="form.creator" placeholder="请输入创建者" />
        </el-form-item>
        <el-form-item label="创建时间" prop="createDate">
          <el-date-picker clearable
            v-model="form.createDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择创建时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :title ="title" :visible.sync="openEncode" width="500px" @close ="handleEncodeDismiss()" append-to-body>
      <el-form ref="encodeForm" :model="encodeForm" :rules="rules" label-width="80px">

        <el-form-item label="序号" prop="index">
          <el-input v-model="encodeObj.index" readonly="readonly" />
        </el-form-item>

        <el-form-item label="字段" prop="field">
          <el-select v-model = "encodeObj.fieldId"
                     width="300px"
                     @change = "recodeEncodeField()"
                     placeholder="选择字段">
            <el-option
              v-for = "item in productFieldVoList"
              :label = "item.name"
              :key = "item.id"
              :value = "item.id"
            >
            </el-option>
          </el-select>
          <el-button type="success"
                     plain
                     icon="el-icon-edit"
                     size="mini"
                     style="margin-left: 20px"
                     @click="handleEncodeSelect()">
            确定
          </el-button>
        </el-form-item>

        <el-form-item label="所选指令">

          <el-button v-for="item in encodeForm.encodeObjs" style="margin-left: 10px; margin-bottom: 10px;">
            序号:{{item.index}}     字段id:{{item.fieldId}}  长度:{{item.len}}    字段名称:{{item.fieldName}}
          </el-button>

        </el-form-item>

        <el-form-item>
          <el-button
            type="success"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleEncodeSubmit()">
            生成
          </el-button>
          <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            @click="handleEncodeRevoke()">
            撤销
          </el-button>
          <el-button
            type="success"
            plain
            icon="el-icon-delete"
            size="mini"
            @click="handleEncodeDelete()">
            删除
          </el-button>
        </el-form-item>

      </el-form>
    </el-dialog>

    <el-dialog :title ="title" :visible.sync="openDecode" width="600px" @close ="handleDecodeDismiss()" append-to-body>
      <el-form ref="decodeForm" :model="decodeForm" :rules="rules" label-width="80px">

        <el-form-item label="序号" prop="index">
          <el-input v-model="decodeObj.index" readonly="readonly" />
        </el-form-item>

        <el-form-item label="截获类型" prop="trimType">
          <el-select v-model="decodeObj.trimType" placeholder="请选择指令类型">
            <el-option
              v-for="dict in dict.type.iot_trim_type"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="截获参数" prop="trimParam">
          <el-input v-model="decodeObj.trimParam"  />
        </el-form-item>


        <el-form-item label="字段" prop="field">
          <el-select v-model = "decodeObj.fieldId"
                     width="300px"
                     @change = "recodeDecodeField()"
                     placeholder="选择字段">
            <el-option
              v-for = "item in productFieldVoList"
              :label = "item.name"
              :key = "item.id"
              :value = "item.id"
            >
            </el-option>
          </el-select>
          <el-button type="success"
                     plain
                     icon="el-icon-edit"
                     size="mini"
                     style="margin-left: 20px"
                     @click="handleDecodeSelect()">
            确定
          </el-button>
        </el-form-item>

        <el-form-item label="所选指令">
          <el-button v-for="item in decodeForm.decodeObjs" style="margin-left: 10px; margin-bottom: 10px;">
            序号:{{item.index}}
            截获类型:{{dict.type.iot_trim_type[item.trimType - 1].label}}
            截获参数:{{item.trimParam}}
            字段id:{{item.fieldId}}     字段名称:{{item.fieldName}}
          </el-button>

        </el-form-item>

        <el-form-item>
          <el-button
            type="success"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleDecodeSubmit()">
            生成
          </el-button>



          <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            @click="handleDecodeRevoke()">
            撤销
          </el-button>
          <el-button
            type="success"
            plain
            icon="el-icon-delete"
            size="mini"
            @click="handleDecodeDelete()">
            删除
          </el-button>
        </el-form-item>

      </el-form>
    </el-dialog>

  </div>
</template>

<script>
import { listCmd, getCmd, delCmd, addCmd, updateCmd, cmdEncodeJson,cmdDecodeJson,getCmdExplain} from "@/api/iot/cmd";

export default {
  name: "Cmd",
  dicts: ['iot_message_type', 'iot_message_by','iot_trim_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 指令表格数据
      cmdList: [],
      // 产品标识
      productList:[],
      //数据包与指令关联
      productFields:[],
      //指令字段
      productFieldVoList:[],
      //包中字段的元素
      productFieldVo : {},
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        productId: null,
        resultId: null,
        name: null,
        sponsor: null,
        cmdType: null,
        cmdHex: null,
        creator: null,
        createDate: null,
        updater: null,
        updateDate: null
      },
      //是否显示编码
      openEncode: false,
      //编码表单
      encodeForm: {
        cmdId: null,
        encodeObjs:[]
      },
      //编码对象
      encodeObj: {
        index: 1,
        len : null,
        fieldId: null,
        fieldName: null,
      },

      //是否显示解码
      openDecode: false,
      //解码表单
      decodeForm:{
        cmdId: null,
        decodeObjs: []
      },
      //解码对象
      decodeObj: {
        index: 1,
        trimType: 1,
        trimParam: null,
        fieldId: null,
        fieldName: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询指令列表 */
    getList() {
      this.loading = true;
      listCmd(this.queryParams).then(response => {
        this.cmdList = response.rows;
        this.productList = response.productList;
        this.productFields = response.productFields;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        productId: null,
        resultId: null,
        name: null,
        sponsor: null,
        cmdType: null,
        cmdHex: null,
        remark: null,
        creator: null,
        createDate: null,
        updater: null,
        updateDate: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加指令";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getCmd(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改指令";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateCmd(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCmd(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    //展示查看的弹出框
    showLookCmdDialog(row) {
      getCmdExplain(row.id).then(response => {
        alert(JSON.stringify(response.data));
      });
    },
    //展示编辑的弹出框
    showEditCmdDialog(row) {
      for(let i = 0; i < this.productFields.length; i++) {
        let item =   this.productFields[i];
        if( item.productId == row.productId + "") {
          this.productFieldVoList = item.productFieldVoList;
        }
      }
      if(row.sponsor == 1) {
        this.decodeForm.cmdId = row.id;
        this.openDecode = true;
      }

      if(row.sponsor == 2) {
        this.encodeForm.cmdId = row.id;
        this.openEncode = true;
      }

    },
    //记录字段
    recodeEncodeField() {
      for(let i = 0; i <  this.productFieldVoList.length; i++) {
        if(this.encodeObj.fieldId  == this.productFieldVoList[i].id){
          this.productFieldVo = this.productFieldVoList[i];
        }
      }
    },
    //记录字段
    recodeDecodeField() {
      for(let i = 0; i <  this.productFieldVoList.length; i++) {
        if(this.decodeObj.fieldId  == this.productFieldVoList[i].id){
          this.productFieldVo = this.productFieldVoList[i];
          this.decodeObj.trimParam = this.productFieldVo.len;
        }
      }
    },
    //确定某一字段
    handleEncodeSelect(){

      let item = {};
      item.index = this.encodeObj.index;

      item.len = this.productFieldVo.len;
      item.fieldId = this.productFieldVo.id;
      item.fieldName = this.productFieldVo.name;

      this.encodeForm.encodeObjs.push(item);
      this.encodeObj.index = this.encodeObj.index + 1;
    },
    handleDecodeSelect(){

      let item = {};
      item.index = this.decodeObj.index;

      item.trimType = this.decodeObj.trimType;
      item.trimParam = this.decodeObj.trimParam;

      item.fieldId =  this.productFieldVo.id;
      item.fieldName =  this.productFieldVo.name;

      this.decodeForm.decodeObjs.push(item);
      this.decodeObj.index = this.decodeObj.index + 1;
    },

    //生成编码的指令
    handleEncodeSubmit(){
      cmdEncodeJson(this.encodeForm).then(response => {
        alert(JSON.stringify(response.data));
        this.handleEncodeDismiss();
      })
    },
    //生产解码的指令
    handleDecodeSubmit(){
      cmdDecodeJson(this.decodeForm).then(response => {
        alert(JSON.stringify(response.data));
        this.handleDecodeDismiss();
      })
    },
    //生成某一指令
    handleEncodeDismiss(){
      this.handleEncodeDelete();
      this.openEncode = false;
    },
    //生成某一指令
    handleDecodeDismiss(){
      this.handleDecodeDelete();
      this.openDecode = false;
    },
    //移除掉最后的指令
    handleEncodeRevoke(){
      this.encodeForm.encodeObjs.splice(this.encodeForm.encodeObjs.length - 1, 1);
      this.encodeObj.index = this.encodeObj.index - 1;
    },
    //移除掉最后的指令
    handleDecodeRevoke(){
      this.decodeForm.decodeObjs.splice(this.decodeForm.decodeObjs.length - 1, 1);
      this.decodeObj.index = this.decodeObj.index - 1;
    },
    //全部移除
    handleEncodeDelete(){
      this.encodeForm.encodeObjs = null;
      this.encodeForm.encodeObjs = [];
      this.encodeObj.index = 1;
    },
    //全部移除
    handleDecodeDelete(){
      this.decodeForm.decodeObjs = null;
      this.decodeForm.decodeObjs = [];
      this.decodeObj.index = 1;
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除指令编号为"' + ids + '"的数据项？').then(function() {
        return delCmd(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('iot/cmd/export', {
        ...this.queryParams
      }, `cmd_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
